<template>
  <div class="building-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <i class="el-icon-office-building"></i>
          楼栋管理
        </h1>
        <p class="page-subtitle">管理社区内的所有楼栋信息</p>
      </div>
      <el-button type="primary" size="large" @click="openDialog()" class="add-btn">
        <i class="el-icon-plus"></i>
        新增楼栋
      </el-button>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-container">
      <div class="stat-card" v-for="(stat, index) in stats" :key="index">
        <div class="stat-icon" :style="{ backgroundColor: stat.color }">
          <i :class="stat.icon"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stat.value }}</div>
          <div class="stat-label">{{ stat.label }}</div>
        </div>
      </div>
    </div>

    <!-- 楼栋卡片网格 -->
    <div class="buildings-grid">
      <div 
        v-for="building in tableData" 
        :key="building.id" 
        class="building-card"
        @click="openDialog(building)"
      >
        <div class="building-3d">
          <div class="building-front">
            <div class="building-windows">
              <div class="window-row" v-for="floor in getFloorCount(building)" :key="floor">
                <div class="window" v-for="window in 4" :key="window"></div>
              </div>
            </div>
            <div class="building-door"></div>
          </div>
          <div class="building-side"></div>
          <div class="building-top"></div>
        </div>
        <div class="building-info">
          <h3 class="building-name">{{ building.blName }}</h3>
          <div class="building-details">
            <div class="detail-item">
              <i class="el-icon-user"></i>
              <span>{{ building.amName || '未分配' }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-office-building"></i>
              <span>{{ building.blType }}</span>
            </div>
            <div class="detail-item">
              <i class="el-icon-date"></i>
              <span>{{ building.blYear }}年</span>
            </div>
          </div>
          <div class="building-actions">
            <el-button size="small" type="primary" @click.stop="openDialog(building)">
              <i class="el-icon-edit"></i>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click.stop="handleDelete(building.id)">
              <i class="el-icon-delete"></i>
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="600px"
      class="building-dialog"
    >
      <el-form :model="form" label-width="100px" class="building-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="楼栋名称" required>
              <el-input v-model="form.blName" placeholder="请输入楼栋名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建筑类型" required>
              <el-select v-model="form.blType" placeholder="请选择建筑类型" style="width: 100%">
                <el-option label="住宅楼" value="住宅楼" />
                <el-option label="商业楼" value="商业楼" />
                <el-option label="办公楼" value="办公楼" />
                <el-option label="综合楼" value="综合楼" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="建筑年份" required>
              <el-date-picker
                v-model="form.blYear"
                type="year"
                format="YYYY"
                value-format="YYYY"
                placeholder="选择年份"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理员" required>
              <el-select v-model="form.amId" placeholder="请选择管理员" @change="handleManagerChange" style="width: 100%">
                <el-option v-for="manager in areaManagers" :key="manager.id" :label="manager.amName" :value="manager.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="建筑描述">
          <el-input 
            v-model="form.blDesc" 
            type="textarea" 
            :rows="3"
            placeholder="请输入建筑描述信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { postRequest, putRequest, deleteRequest, getRequest } from '@/utils/request';

const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const dialogVisible = ref(false);
const dialogTitle = ref('新增楼栋');
const form = reactive({
  id: null,
  areaId: '',
  amId: '',
  amName: '',
  blName: '',
  blType: '',
  blYear: '',
  blDesc: ''
});
const areaManagers = ref([]);

// 统计数据
const stats = computed(() => [
  {
    label: '总楼栋数',
    value: total.value,
    icon: 'el-icon-office-building',
    color: '#409EFF'
  },
  {
    label: '住宅楼',
    value: tableData.value.filter(b => b.blType === '住宅楼').length,
    icon: 'el-icon-house',
    color: '#67C23A'
  },
  {
    label: '商业楼',
    value: tableData.value.filter(b => b.blType === '商业楼').length,
    icon: 'el-icon-shopping-bag-1',
    color: '#E6A23C'
  },
  {
    label: '办公楼',
    value: tableData.value.filter(b => b.blType === '办公楼').length,
    icon: 'el-icon-office-building',
    color: '#F56C6C'
  }
]);

// 根据建筑年份计算楼层数（模拟）
const getFloorCount = (building) => {
  if (!building.blYear) return 6;
  const year = parseInt(building.blYear);
  const currentYear = new Date().getFullYear();
  const age = currentYear - year;
  // 根据建筑年份计算楼层数，越新的建筑楼层越高
  return Math.max(3, Math.min(20, 6 + Math.floor(age / 10)));
};

function fetchData() {
  postRequest('/building/getBuildingByPage', { current: currentPage.value, size: pageSize.value }).then(res => {
    if (res && res.data) {
      tableData.value = Array.isArray(res.data.data.building) ? res.data.data.building : [];
      total.value = res.data.data.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  }).catch(error => {
    console.error('获取数据失败:', error);
    tableData.value = [];
    total.value = 0;
  });
}

function fetchAreaManagers() {
  getRequest('/areaManager/getAreaManagerList').then(res => {
    areaManagers.value = res.data.data.map(element => ({
      id: element.id,
      amName: element.amName
    }));
  }).catch(error => {
    console.error('获取管理员列表失败:', error);
  });
}

function openDialog(row) {
  if (row) {
    dialogTitle.value = '编辑楼栋';
    Object.assign(form, row);
    form.amId = row.amId || '';
    form.amName = row.amName || '';
  } else {
    dialogTitle.value = '新增楼栋';
    form.id = null;
    form.areaId = '';
    form.amId = '';
    form.amName = '';
    form.blName = '';
    form.blType = '';
    form.blYear = '';
    form.blDesc = '';
  }
  dialogVisible.value = true;
}

function handleManagerChange(amId) {
  const selectedManager = areaManagers.value.find(manager => manager.id === amId);
  if (selectedManager) {
    form.amName = selectedManager.amName;
  } else {
    form.amName = '';
  }
}

function handleSubmit() {
  if (!form.blName || !form.blType || !form.blYear || !form.amId) {
    ElMessage.warning('请填写完整信息');
    return;
  }

  if (form.id) {
    putRequest('/building/updateBuildingById', form).then(() => {
      ElMessage.success('更新成功');
      dialogVisible.value = false;
      fetchData();
    }).catch(() => {
      ElMessage.error('更新失败');
    });
  } else {
    postRequest('/building/addBuildingById', form).then(() => {
      ElMessage.success('添加成功');
      dialogVisible.value = false;
      fetchData();
    }).catch(() => {
      ElMessage.error('添加失败');
    });
  }
}

function handleDelete(id) {
  ElMessageBox.confirm('确定要删除该楼栋吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRequest(`/building/deleteBuildingById/${id}`).then(() => {
      ElMessage.success('删除成功');
      fetchData();
    }).catch(() => {
      ElMessage.error('删除失败');
    });
  }).catch(() => {});
}

function handlePageChange(page) {
  currentPage.value = page;
  fetchData();
}

onMounted(() => {
  fetchData();
  fetchAreaManagers();
});
</script>

<style scoped>
.building-container {
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  background: rgba(255, 255, 255, 0.95);
  padding: 20px 30px;
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 5px 0;
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-subtitle {
  margin: 0;
  color: #7f8c8d;
  font-size: 16px;
}

.add-btn {
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  padding: 12px 24px;
  border-radius: 25px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
}

.stats-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.95);
  padding: 20px;
  border-radius: 15px;
  display: flex;
  align-items: center;
  gap: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-label {
  color: #7f8c8d;
  font-size: 14px;
}

.buildings-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.building-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.building-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2);
  border-radius: 20px 20px 0 0;
}

.building-card:hover {
  transform: translateY(-10px) scale(1.02);
  box-shadow: 0 20px 50px rgba(0, 0, 0, 0.2);
}

.building-3d {
  position: relative;
  height: 120px;
  margin-bottom: 20px;
  perspective: 1000px;
}

.building-front {
  position: absolute;
  width: 80px;
  height: 120px;
  background: linear-gradient(135deg, #74b9ff, #0984e3);
  border-radius: 8px 8px 0 0;
  transform: rotateY(-15deg) rotateX(5deg);
  transform-origin: bottom center;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.building-side {
  position: absolute;
  left: 60px;
  width: 20px;
  height: 120px;
  background: linear-gradient(135deg, #0984e3, #74b9ff);
  transform: rotateY(75deg) rotateX(5deg);
  transform-origin: left bottom;
  border-radius: 0 8px 8px 0;
}

.building-top {
  position: absolute;
  left: 0;
  top: -10px;
  width: 80px;
  height: 20px;
  background: linear-gradient(135deg, #74b9ff, #0984e3);
  transform: rotateX(85deg) rotateY(-15deg);
  transform-origin: bottom center;
  border-radius: 8px;
}

.building-windows {
  padding: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.window-row {
  display: flex;
  justify-content: space-between;
  gap: 5px;
}

.window {
  width: 8px;
  height: 8px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 2px;
  animation: windowGlow 3s infinite alternate;
}

.window:nth-child(2n) {
  animation-delay: 1s;
}

.window:nth-child(3n) {
  animation-delay: 2s;
}

@keyframes windowGlow {
  0% { background: rgba(255, 255, 255, 0.3); }
  100% { background: rgba(255, 255, 255, 0.9); }
}

.building-door {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 25px;
  background: #2d3436;
  border-radius: 8px 8px 0 0;
}

.building-info {
  text-align: center;
}

.building-name {
  margin: 0 0 15px 0;
  font-size: 18px;
  font-weight: 700;
  color: #2c3e50;
}

.building-details {
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #7f8c8d;
  font-size: 14px;
}

.building-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.building-dialog {
  border-radius: 15px;
}

.building-form {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .stats-container {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .buildings-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .stats-container {
    grid-template-columns: 1fr;
  }
  
  .building-card {
    padding: 20px;
  }
}
</style>
